package com.imooc.controller;

import com.alibaba.fastjson.JSONObject;
import com.imooc.domain.*;
import com.imooc.repository.DormitoryInfoRepository;
import com.imooc.repository.PreRegistRepository;
import com.imooc.repository.RelationshipRepository;
import com.imooc.repository.StudentRepository;
import com.imooc.service.PreRegistService;
import com.imooc.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by BINGO on 2017/8/5 ${time}.
 */
@CrossOrigin
@RestController
public class PreRegistController {

    @Autowired
    private PreRegistRepository preRegistRepository;

    @Autowired
    private RelationshipRepository relationshipRepository;

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private DormitoryInfoRepository dormitoryInfoRepository;

    @Autowired
    private PreRegistService preRegistService;

    @GetMapping(value = "preregist/{id}")
    public Result<PreRegist> preregistFindOne(@PathVariable("id") String examineeId) {
        return ResultUtil.success(preRegistRepository.findByexamineeId(examineeId));
    }

    @GetMapping(value = "relationship/{id}")
    public Result<Relationship> relationshipFindList(@PathVariable("id") Integer registerId) {
        return ResultUtil.success(relationshipRepository.findByregisterId(registerId));
    }

    @PostMapping(value = "preRegistSave")
    public Result preRegistSave(String relationStr, String registStr) {
        List<Relationship> relationshipList = JSONObject.parseArray(relationStr, Relationship.class);
        PreRegist preRegist = JSONObject.parseObject(registStr, PreRegist.class);
        preRegistService.saveAll(preRegist, relationshipList);
        return ResultUtil.success();
    }

    @GetMapping(value = "txl/students/{id}")
    public Result<Student> findStudentTxlbyClassId(@PathVariable("id") String classId) {
        return ResultUtil.success(studentRepository.findByclassName(classId));
    }

    @GetMapping(value = "txl/dormitory/{id}")
    public Result<Student> findDormitoryTxlbyId(@PathVariable("id") String examineeId) {
        DormitoryInfo dormitoryInfo = dormitoryInfoRepository.findByexamineeId(examineeId);
        if (null != dormitoryInfo) {
            return ResultUtil.success(dormitoryInfoRepository.findByroomId(dormitoryInfo.getRoomId()));
        }
        return ResultUtil.success();
    }

}
